<template>
  <el-drawer
    ref="drawerBox"
    v-bind="$attrs"
    :wrapper-closable="true"
    :close-on-press-escape="false"
    :title="title"
    :size="showMobilePage?'100%':'80%'"
    append-to-body
    v-on="$listeners"
    @closed="handleClose"
  >
    <div class="drawer-content">
      <filter-input
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
      />
      <el-tabs v-if="multiple" v-model="curTabName" type="card" class="contract-detail-tabs-container" style="margin: 8px 0px" @tab-click="onSubActiveOrderChange">
        <el-tab-pane label="账号列表" name="all"/>
        <el-tab-pane v-if="!hideSelectTab" name="selected">
          <div slot="label" class="flex-center">已选择<el-badge v-if="selectedData.length" :value="selectedData.length" /></div>
        </el-tab-pane>
      </el-tabs>
      <div :style="multiple?'':{marginTop: '17px'}" class="table-list">
        <div v-loading="listLoading">
          <template v-if="(isAllTab && list.items.length > 0) || (isSelectedTab && selectedData.length > 0)">
            <u-table
              ref="accountTableRef"
              :data="isAllTab?list.items:selectedTableData"
              :row-class-name="(data) => tableRowClassName(data)"
              :height="setTableHeight"
              :border="true"
              class="fb-table"
              beautify-table
              header-drag-style
              header-cell-class-name="order-data-header-cell"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              fit
              select-callback
              hightlight-current-rowref="tableRef"
              @sort-change="sortMethod"
              @select="selectTable"
              @select-all="selectTable">
              <u-table-column
                v-if="multiple && !hideSelectTab"
                fixed="left"
                align="center"
                type="selection"
                width="50"
              />
              <u-table-column v-else-if="!hideSelectTab" fixed="left" align="left" label="" min-width="50">
                <template slot-scope="scope">
                  <el-radio v-model="singleSelectId" :label="scope.row.mediumId" @change="changeRadio($event, scope.row)"><span/></el-radio>
                </template>
              </u-table-column>
              <template v-if="$slots.tableColumn">
                <slot name="tableColumn" />
              </template>
              <template v-else>
                <u-table-column align="left" label="账号名称" min-width="120">
                  <template slot-scope="scope">
                    <ToolTip :content="scope.row.baseInfo.accountName"/>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="平台" min-width="120">
                  <template slot-scope="scope">
                    <div class="flex">
                      <platformIcon :data="scope.row.platformTypeName" />
                      <ToolTip :content="scope.row.platformTypeName"/>
                    </div>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="账号ID" min-width="120">
                  <template slot-scope="scope">
                    <ToolTip :content="scope.row.baseInfo.accountId"/>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="链接" min-width="150">
                  <template slot-scope="scope">
                    <ToolTip :content="scope.row.resourceLink" :is-can-click="!!scope.row.resourceLink" @handelClick="openLink(scope.row.resourceLink)"/>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="运营模式" min-width="150">
                  <template slot-scope="scope">
                    <ToolTip :content="scope.row.operateModeName"/>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="是否挂靠" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row.microTask ? '是' : '否' }}</span>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="签约状态" min-width="160">
                  <template slot-scope="scope">
                    <el-tooltip v-if="scope.row.signDetailStatus || scope.row.signDetailStatus === 0" :open-delay="800" class="sign-status-tooltip" placement="top">
                      <div slot="content" class="tooltip-content">
                        <div class="account-item-tip"> {{ scope.row.signDetailStatus | signStatusFilter }} <br></div>
                      </div>
                      <div>
                        <StatusText
                          :color="getColor(scope.row.signDetailStatus)"
                          :text="scope.row.signDetailStatus | signStatusFilter"
                        />
                      </div>
                    </el-tooltip>
                    <div v-else>--</div>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="签单签约经纪" min-width="120">
                  <template slot-scope="scope">
                    <ToolTip :content="scope.row.additionalKey.contractBroker"/>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="签约有效期" min-width="200">
                  <template slot-scope="scope">
                    <ToolTip :content="`${format(scope.row.additionalKey.signStartDate || scope.row.signStartDate, 'YYYY/MM/DD')}-${format(scope.row.additionalKey.signEndDate || scope.row.signEndDate, 'YYYY/MM/DD')}`"/>
                  </template>
                </u-table-column>
                <u-table-column align="left" label="关联合同" min-width="140">
                  <template slot-scope="scope">
                    <ToolTip :content="scope.row.legalCode ? scope.row.legalCode.contractCode : ''" :is-can-click="!!scope.row.legalCode" @handelClick="toContractDetail(scope.row.legalCode)" />
                  </template>
                </u-table-column>
                <u-table-column align="left" label="合作方式" min-width="120">
                  <template slot-scope="scope">
                    <ToolTip :content="scope.row.additionalKey.cooperationOption | cooperationStatusFilter"/>
                  </template>
                </u-table-column>
              </template>
            </u-table>
          </template>
          <div v-else style="margin-bottom: 24px;text-align: center;">
            <empty-placeholder text="暂无数据" />
          </div>
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-if="isAllTab"
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            :small="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
          <el-pagination
            v-if="curTabName == 'selected'"
            v-show="selectedData.length > 0"
            :current-page="selectedPage"
            :page-size="selectedPerPage"
            :total="selectedData.length"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            :small="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-row>
        <fixed-pagination v-if="isAllTab" class="bottom-pagination">
          <div class="delete-button-container">
            <template v-if="!hideSelectTab">
              <el-button :disabled="!multiple && !singleSelect.mediumId || multiple && !hasSeleted" :loading="btnLoading" size="small" type="primary" class="related-btn" @click="handleSubmit">确认</el-button>
              <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
            </template>
          </div>
          <el-pagination
            v-if="!showMobilePage && isAllTab"
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
        <fixed-pagination v-if="curTabName == 'selected'" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!hasSeleted" :loading="btnLoading" size="small" type="primary" class="related-btn" @click="handleSubmit">{{ confirmText }}</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
          </div>
          <el-pagination
            v-if="!showMobilePage"
            v-show="selectedData.length > 0"
            :current-page="selectedPage"
            :page-size="selectedPerPage"
            :total="selectedData.length"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getResourceListPost, getOperateoptions } from '@/api/resource';
import tableSelections from '@/mixins/tableSelections';
import { standardFormatNoHour, format } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { getDeptFullName } from '@/filters/dept';
import { mapOptions } from '@/filters';
import { contractType, signStatusFilter, getSignUpColor } from '@/filters/status';
import TableAdaptive from '@/mixins/tableAdaptive';
import options from '@/views/legal/module/options';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ResourceInfo from '@/components/ResourceInfo';
import platformIcon from '@/components/Common/platformIcon';
import FilterInput from '@/components/Tool/filter';
import axios from 'axios';
import { mapState } from 'vuex';
import { cooperationStatusFilter } from '@/utils/accountCommonData';
import mobileTable from '@/mixins/mobileTable';
import { encryption } from '@/utils';
import { platformList } from '@/api/select';

export default {
  name: 'RelatedContract',
  filters: {
    standardFormatNoHour,
    getDeptFullName,
    moneyFilter,
    contractType,
    mapOptions,
    signStatusFilter,
    cooperationStatusFilter,
    format
  },
  components: {
    FilterInput,
    EmptyPlaceholder,
    ResourceInfo,
    platformIcon
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  props: {
    title: {
      type: String,
      default: '选择账号'
    },
    multiple: {
      type: Boolean,
      default: true
    },
    confirmText: {
      type: String,
      default: '确认'
    },
    hideSelectTab: {
      type: Boolean,
      default: false
    },
    expendFilter: {
      type: Array,
      default: null
    },
    expandParams: {
      type: Object,
      default: null
    },
    isContractModule: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      filterInput: {},
      otherFilterInput: {},
      singleSelect: {
        mediumId: ''
      }, // 单选
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      platformList: [],
      selectedPage: 1,
      selectedPerPage: 20,
      sortType: '',
      sortName: '',
      listLoading: false,
      options,
      idKey: 'mediumId', // 多选框参数
      isUmyTable: true,
      tableRefName: 'accountTableRef',
      curTabName: 'all',
      selectedData: [],
      operateModeList: [],
      cancelToken: null,
      btnLoading: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.multiple ? (this.showMobilePage ? 270 : 206) : 175;
    },
    isAllTab() {
      return this.curTabName === 'all';
    },
    isSelectedTab() {
      return this.curTabName === 'selected';
    },
    hasSeleted() {
      return this.multipleSelectionAll.length > 0;
    },
    filterList() {
      let arr = [
        { keyword: 'resourceName', name: '账号名称', type: 'input', labelWidth: '99px' },
        { keyword: 'code', name: '账号ID', type: 'input', labelWidth: '99px' },
        { keyword: 'link', name: '链接', type: 'input', labelWidth: '99px' },
        { keyword: 'platformIds', name: '平台', valueName: 'id', labelName: 'value',
          type: 'mulSelect', options: this.platformList }
      ];
      if (this.isContractModule) { // kol合同关联账号无链接筛选
        arr = arr.filter(item => item.keyword !== 'link');
      }
      if (this.expendFilter && this.expendFilter.length) {
        arr = arr.concat(this.expendFilter);
      }
      return arr;
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    paramsObj: {
      get() {
        return this.filterInput;
      },
      set(data) {
        this.filterInput = data;
      }
    },
    singleSelectId: {
      get() {
        return this.singleSelect.mediumId;
      },
      set(mediumId) {
        //
      }
    }
  },
  created() {
    this.getPlatform();
  },
  methods: {
    format,
    signStatusFilter,
    getSignUpColor,
    // 初始获取数据
    init(data) {
      this.curTabName = 'all';
      this.fetchData();
      this.getOperateoptions();
      if (this.multiple) {
        this.selectedData = data;
        this.multipleSelectionAll = data;
      } else {
        this.singleSelect = data || {};
      }
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      if (this.curTabName === 'all') {
        this.fetchData();
      }
    },
    handleLimit(row) {
      if (!row.contractEffectEndDate && !row.contractEffectStartDate) {
        return '/';
      }
      return '-';
    },
    // fitter
    queryClick() {
      if (this.isSelectedTab) this.curTabName = 'all';
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      this.filterInput = {};
      this.queryClick();
    },
    // 翻页
    handleData(tableData) {
      return tableData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    getColor(status) {
      status = this.signStatusFilter(status);
      return this.getSignUpColor(status);
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.perPage = val;
        this.fetchData(true);
      } else if (this.isSelectedTab) {
        this.selectedPerPage = val;
        this.setSelectRow(this.selectedTableData);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.page = toPage;
        this.fetchData();
      } else if (this.isSelectedTab) {
        this.selectedPage = toPage;
        this.setSelectRow(this.selectedTableData);
      }
    },
    getOperateoptions() {
      getOperateoptions().then(res => {
        this.operateModeList = res.data;
      });
    },
    // 获取列表数据
    fetchData(reset = false) {
      try {
        if (reset) this.page = 1;
        this.listLoading = true;
        const params = JSON.parse(JSON.stringify(this.paramsObj));
        params.page = this.page;
        params.perPage = this.perPage;
        params.sortName = this.sortName;
        params.sortType = this.sortType;
        if (this.cancelToken) this.cancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        if (params.platformIds && params.platformIds.length) {
          params.optionsObj = [{ key: 'pingtai', value: params.platformIds.join(',') }];
        }
        delete params.platformIds;
        this.cancelToken = source;
        if (this.expandParams) {
          Object.keys(this.expandParams).forEach(i => {
            params[i] = this.expandParams[i];
          });
        }
        getResourceListPost(params, source.token).then(({ data }) => {
          this.list = data;
          if (!this.multiple && data.items.length && this.singleSelect.mediumId) {
            const selectData = data.items.find(i => i.mediumId === this.singleSelect.mediumId);
            if (selectData) this.singleSelect = selectData;
          }
          if (this.updateId) {
            this.updateItem();
          }
          this.listLoading = false;
          if (!this.isSelectedTab) this.setSelectRow(data.items);
        }, () => {
          this.listLoading = false;
        }).catch(e => {
          console.error(e);
        });
      } catch (error) {
        console.log(error);
      }
    },
    handleSubmit() {
      this.btnLoading = true;
      const data = this.multiple ? this.selectedData : this.singleSelect;
      this.$emit('submit', data);
    },
    changeRadio(e, data) {
      this.singleSelect = data;
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      }
      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;

      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    handleClose() {
      this.btnLoading = false;
    },
    onBackClick() {
      this.$refs.drawerBox.closeDrawer();
    },
    openLink(link) {
      window.open(link, '_blank');
    },
    toContractDetail(data) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: { id: encryption(data.businessId) },
        query: { processId: encryption(data.processId) }
      });
      window.open(routeUrl.href, '_blank');
    },
    getPlatform() {
      // 获取所属平台
      platformList().then(({ code, data }) => {
        this.platformList = data;
      });
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  transform: translateY(5px);
}
.tip {
  color: #999;
  font-size: 13px;
  margin-left: 20px;;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    &::v-deep {
     .el-table__header {
        .el-checkbox__inner {
          position: relative;
          left: -2px;
        }
      }
    }
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    ::v-deep .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
.contract-detail-tabs-container {
  &::v-deep {
    .el-tabs__header  {
      margin-bottom: 0 !important;
      border-bottom: 1px solid #ddd;
      .el-tabs__nav {
        border: none !important;
        height: 32px !important;
      }
      .el-tabs__item {
        padding: 0 12px !important;
        height: 32px !important;
        line-height: 32px !important;
        margin-right: 8px;
        border: 1px solid #ddd;
        border-radius: 4px 4px 0px 0px;
        color: #333;
        background: #f7f8fa;
        font-size: 16px;
        &:last-child {
          margin-right: 0px;
        }
        &.is-active {
          border-bottom-color: #FFFFFF !important;
          font-weight: bold;
          background: #fff;
          color: #406eff;
        }
      }
    }
  }
}
</style>
